# coding=utf-8
# 表情识别

import cv2
from tensorflow.keras.models import load_model
import numpy as np
import chineseText
import datetime

startTime = datetime.datetime.now()
emotion_classifier = load_model(
    'classifier/emotion_models/simple_CNN.530-0.65.hdf5')
endTime = datetime.datetime.now()
print(endTime - startTime)

emotion_labels = {
    0: '生气',
    1: '厌恶',
    2: '恐惧',
    3: '开心',
    4: '难过',
    5: '惊喜',
    6: '平静'
}


def discern(img):
    grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # OpenCV人脸识别分类器
    classifier = cv2.CascadeClassifier(
        "D:\\OpenCV\\Anaconda3\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_default.xml"
    )
    color = (0, 255, 0)  # 定义绘制颜色
    # 调用识别人脸
    faceRects = classifier.detectMultiScale(
        grayImg, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
    if len(faceRects):  # 大于0则检测到人脸
        for faceRect in faceRects:  # 单独框出每一张人脸
            x, y, w, h = faceRect
            # 框出人脸
            cv2.rectangle(img, (x, y), (x + h, y + w), color, 2)

    for (x, y, w, h) in faceRects:
        gray_face = grayImg[y:(y + h), x:(x + w)]
        gray_face = cv2.resize(gray_face, (48, 48))
        gray_face = gray_face / 255.0
        gray_face = np.expand_dims(gray_face, 0)
        gray_face = np.expand_dims(gray_face, -1)
        emotion_label_arg = np.argmax(emotion_classifier.predict(gray_face))
        emotion = emotion_labels[emotion_label_arg]
        cv2.rectangle(img, (x + 10, y + 10), (x + h - 10, y + w - 10),
                      (255, 255, 255), 2)
        img = chineseText.cv2ImgAddText(img, emotion, x + h * 0.3, y, color, 20)

    cv2.imshow("image", img)  # 显示图像


# VideoCapture()是用于从视频文件、图片序列、摄像头捕获视频的类；
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
while (1):
    ret, frame = cap.read()

    # cv2.imshow('frame', gray)
    discern(frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()